<?php
/**
 * User: 昊天||597767865@qq.com
 * Date: 2019/8/29
 * Time: 15:41
 */
namespace common\models;
use yii\base\Model;
use Zhuzhichao\IpLocationZh\Ip;

class HtCommon extends Model
{
    /**
     *  根据 ip 获取 当前城市 不需要接口
     * @param $ip
     */
    public static function getAddress($ip)
    {
        if (empty($ip)) self::getCityByIp();
        $res = Ip::find($ip);
        return $res[1].'-'.$res[2];
    }

    /**
     * 需要请求接口
     * 根据 ip 获取 当前城市
     */
    public static function getCityByIp()
    {
        if (! empty($_SERVER["HTTP_CLIENT_IP"])) {
            $cip = $_SERVER["HTTP_CLIENT_IP"];
        } elseif (! empty($_SERVER["HTTP_X_FORWARDED_FOR"])) {
            $cip = $_SERVER["HTTP_X_FORWARDED_FOR"];
        } elseif (! empty($_SERVER["REMOTE_ADDR"])) {
            $cip = $_SERVER["REMOTE_ADDR"];
        } else {
            $cip = "";
        }
        $url = 'http://restapi.amap.com/v3/ip';
        $data = array(
            'output' => 'json',
            'key' => '16199cf2aca1fb54d0db495a3140b8cb',
            'ip' => $cip
        );
        $postData = http_build_query($data);
        $opts = array(
            'http' => array(
                'method' => 'POST',
                'header' => 'Content-type: application/x-www-form-urlencoded',
                'content' => $postData
            )
        );
        $context = stream_context_create($opts);
        $result = file_get_contents($url, false, $context);
        $res = json_decode($result, true);

        if (empty($res['province'])) {
            $res['province'] = '北京市';
        }
        if (! empty($res['province']) && $res['province'] == "局域网") {
            $res['province'] = '北京市';
        }
        if (empty($res['city'])) {
            $res['city'] = '北京市';
        }
        return $res['province'].'-'.$res['city'];
    }

}
